// 监听书签变化，实现增量更新
chrome.bookmarks.onCreated.addListener((id, bookmark) => {
  console.log('书签已创建:', bookmark);
  updateBookmarkCache('add', bookmark);
});

chrome.bookmarks.onRemoved.addListener((id, removeInfo) => {
  console.log('书签已删除:', removeInfo);
  updateBookmarkCache('remove', { id });
});

chrome.bookmarks.onChanged.addListener((id, changeInfo) => {
  console.log('书签已更改:', id, changeInfo);
  updateBookmarkCache('update', { id, ...changeInfo });
});

// 更新本地缓存中的书签数据
const updateBookmarkCache = async (
  action: 'add' | 'remove' | 'update',
  data: any
) => {
  try {
    // 获取当前缓存
    const cache = await chrome.storage.local.get('bookmarksCache');
    const bookmarksCache = cache.bookmarksCache || [];
    
    switch (action) {
      case 'add':
        // 在实际应用中，可能需要处理分类等
        bookmarksCache.push(data);
        break;
      case 'remove':
        const index = bookmarksCache.findIndex((b: any) => b.id === data.id);
        if (index !== -1) {
          bookmarksCache.splice(index, 1);
        }
        break;
      case 'update':
        const bookmarkIndex = bookmarksCache.findIndex((b: any) => b.id === data.id);
        if (bookmarkIndex !== -1) {
          bookmarksCache[bookmarkIndex] = { 
            ...bookmarksCache[bookmarkIndex],
            ...data 
          };
        }
        break;
    }
    
    // 保存更新后的缓存
    await chrome.storage.local.set({ bookmarksCache });
  } catch (err) {
    console.error('更新书签缓存失败:', err);
  }
}; 